#!/usr/bin/env python
#-*- coding:utf-8 -*-

"""
	PROJECT pyevocomm -

	APP		Main 

	MODULE	Node Controller

	SITE DESCRIPTION http://code.google.com/p/pyevocomm/ 

	@copyright: 2012 by archetipo <alessio.gerace@gmail.com>
	@license: New BSD License, see COPYING for details.
"""


import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..'))

# stdlib
import copy
import random


# pyglet related
import pyglet
from pyglet.window import key

# cocos2d related
from cocos.layer import Layer
from cocos.scene import Scene
from cocos.euclid import Point2

# pyevocomm related
import Tlib.Dprime.utils as utils # module from above
import Tlib.Dprime.TServerCtrl as Sctrl

__all__ = ['MainCtrl']

#
# Controller ( MVC )
#

class MainCtrl( Layer ):

	is_event_handler = True #: enable pyglet's events

	def __init__(self, model):
		super(MainCtrl,self).__init__()

		self.used_key = False
		self.paused = False

		self.model = model
		self.elapsed = 0
		Sctrl.ThController(self).start()
		print 'partito'
		
	def recdata(self,data):
		if self.paused:
			return False

		if self.used_key:
			return False
			
		if data['tipo']=='rigth': 
			self.model.rigth(data)
		elif data['tipo']=='left': 
			self.model.left(data)
		elif data['tipo']=='single': 
			self.model.single(data)
		elif data['tipo']=='select': 
			self.model.select(data)
		elif data['tipo']=='close': 
			self.model.close(data)            
		elif data['tipo']=='lang': 
			self.model.lang(data)            
		elif data['tipo']=='step': 
			self.model.step(data)            
		elif data['tipo']=='insel': 
			self.model.insel(data)
		elif data['tipo']=='lost': 
			self.model.lost(data)
		elif data['tipo']=='menu': 
			self.model.menu(data)
		else:
			return False
		return True
		
	def on_key_press(self, k, m ):
		if self.paused:
			return False

		if self.used_key:
			return False

		if k in (key.LEFT, key.RIGHT, key.DOWN, key.UP, key.SPACE,key.M):
			if k == key.LEFT:
				self.model.close(utils.datacom.datclose)
			elif k == key.RIGHT:
				self.model.step(utils.datacom.datstep) 
			elif k == key.DOWN:
				self.model.insel(utils.datacom.datinsel)
			elif k == key.UP:
				self.model.select(utils.datacom.datselect)
			elif k == key.SPACE:
				# let the player move the block after it was dropped
				self.model.lost(utils.datacom.datlost)
			elif k == key.M:
				# let the player move the block after it was dropped
				self.model.menu(utils.datacom.datmenu)
			#~ sself.used_key = True
			return True
		return False



	def pause_controller( self ):
		'''removes the schedule timer and doesn't handler the keys'''
		self.paused = True
		self.unschedule( self.step )

	def resume_controller( self ):
		'''schedules  the timer and handles the keys'''
		self.paused = False
		self.schedule( self.step )

	def step( self, dt ):
		'''updates the engine'''
		pass

	def draw( self ):
		'''draw the map and the block'''
		pass
